﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Lamex.Library;
using Lamex.Base;
using Lamex.Interface;
using Lamex.Common;
using Lamex.Library.CommonClass;
using System.IO;
using System.Data.SqlClient;

namespace Lamex.mMES.UI
{
    public partial class frmMES_Project_Log_Add : frmBaseChild
    {
        byte[] buffer = null;
        string strSavePath = ""; //存放本地图片路径，可以全局配置
        string strFileName = "";
        Boolean IsEdit = false;

        public frmMES_Project_Log_Add()
        {
            InitializeComponent();
        }

        private void frmProject_Log_Add_Load(object sender, EventArgs e)
        {
            try { base.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理

            //lookUpEdit2.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard;//设为用户可以编辑
            getLookUpEditValue();
        }

        private void frmMES_Project_Log_Add_Resize(object sender, EventArgs e)
        {
            resetPictureBox();
        }

        private void resetPictureBox()
        {
            pictureBox1.Width = panelControl2.Width - 12;
            pictureBox1.Height = panelControl2.Height - 12;
            pictureBox1.Location = new Point(6, 6);

            if(!(pictureBox1.Image == null))
            {
                if(pictureBox1.Image.Width> pictureBox1.Width || pictureBox1.Image.Height > pictureBox1.Height)
                {
                    pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
                }
                else
                {
                    pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage;
                }
            }
        }

        public void getLookUpEditValue()
        {
            lookUpEdit1.Properties.ValueMember = "项目名称";
            lookUpEdit1.Properties.DisplayMember = "项目名称";
            lookUpEdit1.Properties.DataSource = getProject_List();
            lookUpEdit1.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            lookUpEdit1.Properties.ImmediatePopup = true;
            lookUpEdit1.Properties.NullText = "选择日志项目";
        }

        public DataTable getProject_List()
        {
            string sql = @"SELECT PROJECT_NAME AS 项目名称,PROJECT_LEADER AS 项目负责
FROM DPT_Project_Item_List
WHERE ACTUAL_FINISH_DATE IS NULL
ORDER BY PROJECT_NAME";

            DataTable dt = BaseBuildSql.GetDataTableBySql(sql);
            return dt;
        }

        private void lookUpEdit1_EditValueChanged(object sender, EventArgs e)
        {
            //如果节点日期为空，则默认为当前日期
            if (string.IsNullOrEmpty(dateEdit1.Text))
            {
                dateEdit1.DateTime = System.DateTime.Now;//强制改写节点日期，防止用户忘记修改节点日期，导致不正确记录
            }
            refreshLogDescAndProjectState();
        }

        private void dateEdit1_EditValueChanged(object sender, EventArgs e)
        {
            refreshLogDescAndProjectState();
        }

        private void refreshLogDescAndProjectState()
        {
            //如果项目名称及节点日期同时不为空
            if (!string.IsNullOrEmpty(lookUpEdit1.Text) && !string.IsNullOrEmpty(dateEdit1.Text))
            {
                #region 刷新历史数据

                if (!(string.IsNullOrEmpty(lookUpEdit1.Text)) && !(string.IsNullOrEmpty(dateEdit1.Text)))
                {
                    string sql = @"SELECT DEV_LOG_DESC,DEV_LOG_STATE
FROM DPT_Project_Dev_Log
WHERE PROJECT_NAME='" + lookUpEdit1.EditValue.ToString() + @"'
AND DEV_LOG_DATE='" + dateEdit1.EditValue.ToString() + @"'";

                    DataTable dt = BaseBuildSql.GetDataTableBySql(sql);

                    if (dt.Rows.Count > 0)
                    {
                        memoEdit1.Text = dt.Rows[0]["DEV_LOG_DESC"].ToString();
                        comboBoxEdit1.Text = dt.Rows[0]["DEV_LOG_STATE"].ToString();
                        IsEdit = true;
                    }
                    else
                    {
                        memoEdit1.Text = null;
                        comboBoxEdit1.Text = null;
                        IsEdit = false;
                    }
                }
                else
                {
                    memoEdit1.Text = null;
                    comboBoxEdit1.Text = null;
                    IsEdit = false;
                }

                #endregion
            }
        }

        public override void DoSave(IButtonInfo sender)
        {
            //判断表是否存在
            if (!BuildSqlHelper.IsExistList("DPT_Project_Dev_Log", "LamexMESManager")) return;

            //判断是否截图
            if (strFileName == "")
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("请先获取日志截图！", "提示", MessageBoxButtons.OK);
                return;
            }

            if (string.IsNullOrEmpty(lookUpEdit1.Text) || string.IsNullOrEmpty(dateEdit1.Text) || string.IsNullOrEmpty(memoEdit1.Text) || string.IsNullOrEmpty(comboBoxEdit1.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("日志记录不允许有空值！", "提示", MessageBoxButtons.OK);
                //MessageBox.Show("日志记录不允许有空值！");
                return;
            }

            if (IsEdit == true)
            {
                //已引导用户转到日志明细界面进行修改操作，不再编写
                //删除数据库已有记录，删除原有图片，...
            }

            #region 保存新增或修改记录内容及图片

            string strProject_Name = lookUpEdit1.Text;
            string strLog_Date = dateEdit1.Text;
            string strLog_Desc = memoEdit1.Text;
            string strLog_State = comboBoxEdit1.Text;
            string strC_User = Lamex.Common.Loginer.CurrentUser.AccountName;
            string Insert_Sql = "";

            int m = 0;
            Insert_Sql = @"insert into DPT_Project_Dev_Log (PROJECT_NAME,DEV_LOG_DATE,DEV_LOG_DESC,DEV_LOG_STATE,UPDATE_TIME,UPDATE_USER,IMAGE_NAME) values";
            Insert_Sql = Insert_Sql + " ('" + strProject_Name + "','" + strLog_Date + "','" + strLog_Desc + "','" + strLog_State + "',getdate(),'" + strC_User + "','" + strFileName + "')";
            m = Write1(Insert_Sql);

            if (m == -1)
            {
                if (Loginer.CurrentUser.ChangeLanguage == 0)
                    DevExpress.XtraEditors.XtraMessageBox.Show("项目当前日期日志已存在，如需修改，请跳转到日志明细界面！", "提示", MessageBoxButtons.OK);
                else
                    DevExpress.XtraEditors.XtraMessageBox.Show("Project Log Existed", "Tips", MessageBoxButtons.OK);
            }
            else if (m == 0)
            {
                if (Loginer.CurrentUser.ChangeLanguage == 0)
                    DevExpress.XtraEditors.XtraMessageBox.Show("新增失败", "提示", MessageBoxButtons.OK);
                else
                    DevExpress.XtraEditors.XtraMessageBox.Show("Add Failed", "Tips", MessageBoxButtons.OK);

            }
            else
            {
                //将图片保存到指定路径下
                WriteBytesToFile(strSavePath, buffer);

                if (Loginer.CurrentUser.ChangeLanguage == 0)
                    DevExpress.XtraEditors.XtraMessageBox.Show("新增成功", "提示", MessageBoxButtons.OK);
                else
                    DevExpress.XtraEditors.XtraMessageBox.Show("Add Successed", "Tips", MessageBoxButtons.OK);
            }

            #endregion

            //DoView(null);
            base.DoSave(sender);
        }

        private int Write1(string strSql)
        {
            string sConn = SqlConfiguration.CurrentConnectionString;
            using (SqlConnection conn = new SqlConnection(sConn))
            {
                using (SqlCommand cmd = new SqlCommand(strSql, conn))
                {
                    try
                    {
                        conn.Open();
                        int rows = cmd.ExecuteNonQuery();
                        conn.Close();
                        return rows;
                    }
                    catch (Exception e)
                    {
                        //改为返回-1值提示用户
                        //DevExpress.XtraEditors.XtraMessageBox.Show("当前日期日志已存在，暂不提供修改功能！" 
                        //    + "\r\n" + e.ToString()
                        //    + "\r\n" + e.Message, "提示", MessageBoxButtons.OK);
                        ////throw e;
                        return -1;
                    }
                }
            }
        }

        //基础配置窗体跳转
        private void labelGoto_Click(object sender, EventArgs e)
        {
            //Loginer.CurrentUser.FunctionId = "menuMES_Project_Log_Record";
            MdiTools.OpenChildWebBrowse(this.MdiParent as IMdiForm, new frmBaseChildWinForm("DPT_Project_Dev_Log", 0, true, false), sender as ToolStripMenuItem);
        }

        #region 获取图片并处理

        //点击获取剪贴板内容
        private void btnAutoPic_Click(object sender, EventArgs e)
        {
            //首先清空pictureBox1控件
            pictureBox1.Image = null;

            //获取剪贴板内容
            IDataObject iData = Clipboard.GetDataObject();

            if (iData.GetDataPresent(DataFormats.Bitmap))
            {
                //显示剪贴板图片
                Image img = (Bitmap)iData.GetData(DataFormats.Bitmap);
                pictureBox1.Image = img;
                resetPictureBox();

                buffer = PhotoImageInsert(img);

                //图片保存到本地，改为当用户做保存操作时执行
                strFileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg";
                strSavePath = @"\\TX-FS10\tx-fs1\IMA\MES\ShareResource\Project_Log_Image\" + strFileName;
                //WriteBytesToFile(path, buffer);
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("剪贴板为空，或不是图片内容！", "提示", MessageBoxButtons.OK);
            }
        }

        //图片保存到本地
        public void WriteBytesToFile(string fileName, byte[] content)
        {
            FileStream fs = new FileStream(fileName, FileMode.Create);
            BinaryWriter w = new BinaryWriter(fs);
            try
            {
                w.Write(content);
            }
            finally
            {
                fs.Close();
                w.Close();
            }
        }

        //把picturebox的Image 转换成二进制
        public byte[] PhotoImageInsert(System.Drawing.Image imgPhoto)
        {
            //将Image转换成流数据，并保存为byte[] 
            MemoryStream mstream = new MemoryStream();
            imgPhoto.Save(mstream, System.Drawing.Imaging.ImageFormat.Bmp);
            byte[] byData = new Byte[mstream.Length];
            mstream.Position = 0;
            mstream.Read(byData, 0, byData.Length);
            mstream.Close();
            return byData;
        }

       //数据库图片提取保存
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            string strFilePath = @"\\TX-FS10\tx-fs1\IMA\MES\ShareResource\Project_Log_Image";
            string strPicFile;
            int i;

            string sql = @"SELECT PROJECT_NAME,DEV_LOG_DATE,DEV_LOG_IMAGE
FROM DPT_Project_Dev_Log
WHERE DEV_LOG_IMAGE IS NOT NULL
ORDER BY PROJECT_NAME,DEV_LOG_DATE";

            DataTable dt = BaseBuildSql.GetDataTableBySql(sql);

            for (i = 0; i < Convert.ToInt16(dt.Rows.Count); i++)
            {
                strFileName = dt.Rows[i]["PROJECT_NAME"].ToString() + "_" + i.ToString();
                strPicFile = strFilePath + @"\" + strFileName + ".jpg";

                FileStream fs = new FileStream(strPicFile, FileMode.Create, FileAccess.Write);
                BinaryWriter w = new BinaryWriter(fs);

                byte[] piccontent = (byte[])dt.Rows[i]["DEV_LOG_IMAGE"];

                try
                {
                    w.Write(piccontent);
                }
                finally
                {
                    fs.Close();
                    w.Close();
                }
            }
        }

        #endregion

        //禁用SearchLookUpEdit弹框
        //private void lookUpEdit2_QueryPopUp(object sender, CancelEventArgs e)
        //{
        //    e.Cancel = true;
        //}
    }
}